<template>
  <div class="goods-detail">
    <van-sticky>
      <van-nav-bar :title="$route.meta.title" left-arrow @click-left="onClickLeft" style="width:100%;" />
    </van-sticky>
    <van-cell-group class="goods-detail-items">
      <van-cell title="商品视频" center class="video-name">
        <template #right-icon>
          <van-uploader v-model="videourl" :max-count="1" @click-preview="players = true" @oversize="videosize" :before-delete="beforeDelVideo" :after-read="getVideoUrl" :disabled="disable" accept="video/*" :max-size="10240 * 1024">
            <!-- 封面插槽 -->
            <template #preview-cover>
              <van-image :src="require('@/assets/player.png')" width="100%" height="100%" fit="cover" class="preview-img" />
            </template>
          </van-uploader>
        </template>
      </van-cell>
      <van-cell title="商品图片" center>
        <template #right-icon>
          <van-uploader v-model="imgurls" :max-count="max_count" accept="image/*" @oversize="onOversize" :before-delete="beforeDel" :after-read="afterRead" :deletable="deletable" :max-size="5120 * 1024" />
        </template>
      </van-cell>
      <van-field label="商品名称" v-model="pdata.name" :disabled="disable" input-align="right" />
      <van-field label="商品类型" v-model="pdata.type_name" @click="showtype = true" readonly input-align="right" is-link />
      <van-field label="商品价格" type="number" v-model="pdata.price" input-align="right">
        <template #extra><span style="margin-left: 5px">元</span></template>
      </van-field>
      <van-field label="商品重量" type="number" v-model="pdata.weight" :disabled="disable" input-align="right">
        <template #extra><span style="margin-left: 5px">Kg</span></template>
      </van-field>
      <van-field label="商品主料" type="textarea" autosize v-model="pdata.sidedish" :disabled="disable" input-align="left" />
      <van-field label="商品描述" type="textarea" autosize v-model="pdata.remark" :disabled="disable" input-align="left" />
      <div class="spacing"></div>
      <van-field label="是否特价" input-align="right">
        <template #input>
          <van-radio-group v-model="pdata.issprice" checked-color="#1bb89c" direction="horizontal">
            <van-radio :name="0">否</van-radio>
            <van-radio :name="1">是</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field label="特价价格" v-model="pdata.sprice" type="number" v-if="pdata.issprice == '1'" input-align="right">
        <template #extra><span style="margin-left: 5px">元</span></template>
      </van-field>
      <div class="spacing"></div>
      <van-field label="库存" v-model="pdata.stocknum" type="number" :disabled="disable" input-align="right" />
      <van-field label="生产日期" v-model="pdata.manufacturedate" disabled input-align="right" is-link />
      <van-field label="保质期" v-model="pdata.qualityperiod" disabled input-align="right" is-link />
      <van-field label="优先级" type="number" v-model="pdata.sort" input-align="right" />
      <!-- <van-field label="商品状态" input-align="right">
        <template #input>
          <van-radio-group v-model="pdata.state" checked-color="#1bb89c" direction="horizontal">
            <van-radio :name="1">上架</van-radio>
            <van-radio :name="2">下架</van-radio>
          </van-radio-group>
        </template>
      </van-field> -->
    </van-cell-group>
    <div class="goods-detail-set">
      <div class="set-center">
        <van-button round type="info" color="#1bb89c" @click="onEdit">保 存</van-button>
        <div class="set-spacing"></div>
        <van-button round plain type="info" color="#1bb89c" @click="setState">{{title}}</van-button>
        <div class="set-spacing"></div>
        <van-button round plain type="danger" @click="delGoods">删除</van-button>
      </div>
    </div>
    <!-- 类型选择 -->
    <van-popup v-model="showtype" round position="bottom" :style="{ height: '55%' }">
      <van-picker :columns="typeList" show-toolbar title="选择类型" @confirm="confirm1" @cancel="showtype=false" />
    </van-popup>
    <!-- 视频播放 -->
    <van-popup v-model="players" @close="stopPlay" :close-on-click-overlay="false" :style="{ height: '100%' }" position="bottom" closeable>
      <video ref="curr_video" :src="play_video" autoplay="autoplay" width="100%" height="100%" controls></video>
    </van-popup>
  </div>
</template>

<script>
import { Dialog, Toast } from 'vant'
export default {
  name: 'GoodsDetail',
  data () {
    return {
      play_video: '',
      players: false,
      showtype: false,
      typeList: [],
      disable: false,
      deletable: true,
      max_count: 5,
      gtype: '',
      states: '',
      type: '',
      id: '',
      gid: '',
      title: '',
      pdata: {},
      imgurl: '',
      vdourl: '',
      imgurls: [],
      videourl: [],
      edit_img: [],
      edit_vdo: [],
    };
  },
  methods: {
    onClickLeft () {
      if (this.states == 1) {
        if (this.gtype != null) {
          this.$router.push({ path: '/goods', query: { state: 1, gtype: this.gtype } })
        } else {
          this.$router.push({ path: '/goods', query: { state: 1, gtype: null } })
        }
      } else if (this.states == 2) {
        if (this.gtype != null) {
          this.$router.push({ path: '/goods', query: { state: 2, gtype: this.gtype } })
        } else {
          this.$router.push({ path: '/goods', query: { state: 2, gtype: null } })
        }
      }
    },
    // 图片限制
    onOversize () {
      Toast.fail("图片大小不能超过5M");
    },
    // 视频限制
    videosize () {
      Toast.fail("视频大小不能超过10M");
    },
    confirm1 (val) {
      this.showtype = false;
      this.pdata.type_name = val.text
      this.pdata.type = val.id
    },
    // 删除商品
    delGoods () {
      Dialog.confirm({
        title: '提示',
        message: '确认删除该商品吗？',
      })
        .then(() => {
          this.$axios("/products/pdelete", {
            product_id: this.gid,//区别：1-返回自己的商品类型，2-返回购买时总部/经销商的商品类型
          })
            .then((res) => {
              if (res.data.code == 1) {
                Toast.success('删除成功')
                this.onClickLeft() // 跳转回指定参数的页面
              } else {
                Toast.fail('删除失败' + res.data.msg)
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          // on cancel
        })
    },
    // 获取商品信息
    getGoodsDetail () {
      this.gid = this.$route.query.id
      this.$axios('/products/productsinfo', {
        id: this.gid
      })
        .then(res => {
          this.pdata = res.data.data
          this.edit_img = (this.pdata.menuimage || '').split(',')
          this.imgurls = this.edit_img.map(item => {
            return { url: this.img + item }
          })
          if (this.pdata.menuvideo != null && this.pdata.menuvideo != "") {
            this.edit_vdo = (this.pdata.menuvideo || '').split(',')
            this.videourl = this.edit_vdo.map(item => {
              return { url: this.img + item }
            })
            this.play_video = this.videourl[0].url
          } else {
            this.videourl = []
          }
          if (this.pdata.is_produce == 1) {
            // is_produce  1：自产，2：购买
            this.disable = false
            this.deletable = true
            this.max_count = 5
          } else {
            this.disable = true
            this.deletable = false
            this.max_count = 1
          }
        })
        .catch(err => {
          console.log(err);
        })
    },
    getGoodsType () {
      this.$axios("/products/prodtypelist", {
        type: 1,//区别：1-返回自己的商品类型，2-返回购买时总部/经销商的商品类型
      })
        .then((res) => {
          this.typeList = res.data.data.map(v => {
            return {
              text: v.type_name,
              id: v.id
            }
          })
        })
        .catch((err) => {
          console.log(err);
        });
    },
    beforeDel (val, detail) {
      this.imgurls.splice(detail.index, 1)
      this.edit_img.splice(detail.index, 1)
    },
    beforeDelVideo (val, detail) {
      this.videourl.splice(detail.index, 1)
      this.edit_vdo.splice(detail.index, 1)
    },
    // 图片上传状态
    afterRead (file) {
      file.status = "uploading";
      let params = new FormData();
      params.append("file", file.file);
      this.$notoken("/main/upload", params)
        .then((res) => {
          this.imgurl = res.data.data
          this.edit_img.push(this.imgurl)
        });
      setTimeout(() => {
        file.status = "done";
        file.message = "上传成功";
      }, 1000);
    },
    // 视频上传状态
    getVideoUrl (file) {
      file.status = "uploading";
      let params = new FormData();
      params.append("file", file.file);
      this.$notoken("/main/upload", params)
        .then((res) => {
          this.vdourl = res.data.data
        });
      setTimeout(() => {
        file.status = "done";
        file.message = "上传成功";
      }, 1000);
    },
    // 关闭遮罩层停止播放视频
    stopPlay () {
      if (this.players == false) {
        this.$refs.curr_video.pause()
      }
    },
    // 编辑商品
    onEdit () {
      this.$axios('/products/productsinfo', {
        id: this.gid,
        handle: "ajax",//不带即为返回产品详情数据,带上为修改数据 示例值提交上来即可 
        menuvideo: this.vdourl == '' ? this.edit_vdo[0] : this.vdourl, //产品视频
        menuimage: this.edit_img, // 新图片+旧图片
        name: this.pdata.name,// 商品名
        weight: this.pdata.weight,//重量
        sidedish: this.pdata.sidedish,//商品主料
        remark: this.pdata.remark,//描述
        stocknum: this.pdata.stocknum,//库存
        sort: this.pdata.sort,// 优先级
        price: this.pdata.price,//价格
        issprice: this.pdata.issprice,//是否有特价
        sprice: this.pdata.sprice,//特价价格
        type: this.pdata.type,//产品类型
        manufacturedate: this.pdata.manufacturedate,//生产日期
        qualityperiod: this.pdata.qualityperiod,//保质期
        // state: this.pdata.state,//1-上架；2-下架 
      })
        .then(res => {
          if (res.data.code == 1) {
            Toast.success('保存成功')
            this.getGoodsDetail()
          } else if (res.data.code == -1) {
            Toast.fail('商品审核未通过')
            this.getGoodsDetail()
          }
        })
        .catch(err => {
          console.log(err);
        })
    },
    // 商品上下架
    setState () {
      this.$axios("/products/productsstate", {
        id: this.gid, //产品ID
        state: this.type == 0 ? 2 : 1 //1-上架；2-下架
      })
        .then((res) => {
          if (res.data.code == 1) {
            // if (this.pdata.type != null && this.pdata.type_name != "" && this.type == 0) {
            Toast.success(this.title + '成功')
            setTimeout(() => {
              this.onClickLeft() // 跳转回指定参数的页面
            }, 1000);
            // } else {
            //   Toast.fail('请给商品选择一个类型并保存')
            // }
          } else {
            Toast.fail(res.data.msg)
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  created () {
    this.getGoodsDetail()
    this.getGoodsType()
    this.type = this.$route.query.type
    this.states = this.$route.query.state // 接收当前选择的商品上/下架状态
    this.gtype = this.$route.query.signs // 接收当前选择商品类型的下标
    this.id = this.$route.query.id
    if (this.type == 0) {
      this.title = '下 架'
    } else {
      this.title = '上 架'
    }
  },
}
</script>
<style lang="less" scoped>
.goods-detail {
  display: flex;
  flex-direction: column;
  &-items {
    width: 100%;
    .video-name {
      /deep/ .van-uploader__file-name {
        display: none;
      }
      .preview-img {
        /deep/ .van-image__img {
          border-radius: 15px;
        }
      }
    }
    &-img {
      width: 100%;
      height: 400px;
    }
    /deep/ .van-field__label {
      color: black;
    }
    /deep/ .van-uploader__file,
    /deep/ .van-uploader__upload,
    /deep/ .van-uploader__preview,
    /deep/ .van-uploader__preview-image {
      border-radius: 15px;
      width: 1.1rem;
      height: 1.1rem;
    }
  }
  &-set {
    display: flex;
    flex-direction: column;
    width: 100%;
    margin: 100px auto;
    .set-center {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 100%;
      margin: 0 auto;
      .set-spacing {
        height: 30px;
      }
      /deep/ .van-button {
        width: 80%;
        height: 80px;
        font-weight: bold;
        font-size: 30px;
      }
    }
  }
}
</style>